<template>
  <div>
    <!-- 原始内容插槽 -->
    <slot></slot>

    <!-- 错误球 (开发环境) - 用错误边界保护 -->
    <ErrorBoundary>
      <ErrorBall />
    </ErrorBoundary>

    <!-- 全局错误弹窗 -->
    <GlobalErrorModal
      :visible="showErrorModal"
      :error-info="currentError"
      @close="handleCloseError"
      @reload="handleReload"
    />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue';
  import { useRouter } from 'vue-router';
  import GlobalErrorModal from './index.vue';
  import ErrorBall from './ErrorBall.vue';
  import ErrorBoundary from './ErrorBoundary.vue';
  import { globalErrorHandler, type ErrorInfo } from '@/utils/errorHandler';

  const router = useRouter();

  // 响应式状态
  const showErrorModal = ref(false);
  const currentError = ref<ErrorInfo>({
    message: '',
    timestamp: Date.now(),
    type: '',
  });

  // 显示错误弹窗
  const showError = (errorInfo: ErrorInfo) => {
    currentError.value = errorInfo;
    showErrorModal.value = true;
  };

  // 关闭错误弹窗
  const handleCloseError = () => {
    showErrorModal.value = false;
    globalErrorHandler.closeError();
  };

  // 重新加载页面
  const handleReload = () => {
    showErrorModal.value = false;
    globalErrorHandler.closeError();
    // 页面重新加载将在组件中处理
  };

  // 注册错误处理回调
  onMounted(() => {
    globalErrorHandler.onError(showError);
  });

  onUnmounted(() => {
    globalErrorHandler.offError(showError);
  });
</script>

<style scoped>
  /* 无需额外样式，所有样式在子组件中 */
</style>
